package com.xuedakun.xasdk.net.volley;

import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.xuedakun.xasdk.net.HttpUtils;
import com.xuedakun.xasdk.utils.StringUtils;

import java.util.Map;

/**
 * Created by xuedakun on 2017/6/3 15:22
 * http get请求
 * @version : v1.0
 * @project : xasdk
 * @Email : dakun611@Gmail.com
 */

public class GetRequest<R extends BaseResult> extends AbstractRequest<R>{


    /**
     * 请求主体构造
     *
     * @param host     请求网络接口的host
     * @param method   请求网络接口的方法名
     * @param callback 请求回调
     */
    public GetRequest(String host, String method, VolleyCallback<R> callback) {
        super(host, method, callback);
    }

    @Override
    protected StringRequest getRealRequest() {
        if(stringRequest == null) {
            stringRequest = new StringRequest(Request.Method.GET, getUrl(), callback, callback);
        }
        return stringRequest;
    }

    @Override
    protected String getUrl() {
        String url = host + HttpUtils.URL_DELIMITER + method;
        for(Object urlArgument : urlArguments) {
            url += HttpUtils.URL_DELIMITER + urlArgument.toString();
        }
        boolean isFirstArgument = true;
        for(Map.Entry<String, Object> entry : arguments.entrySet()) {
            if(isFirstArgument) {
                isFirstArgument = false;
                url += "?" + entry.getKey() + "=" + entry.getValue().toString();
            }else {
                url += "&" + entry.getKey() + "=" + entry.getValue().toString();
            }
        }
        return url;
    }

    @Override
    public GetRequest addArgument(String key, Object argument) {
        if (!StringUtils.isObjectToStringNull(argument)) {
            arguments.put(key, StringUtils.encodeString2UTF8(argument.toString()));
        }
        return this;
    }
}
